<template>
    <div>
      <!-- 页面头部 -->
      <Header title="支付方式管理"></Header>
  
      <!-- 操作按钮区域 -->
      <div class="operation-bar">
        <el-button type="success" icon="Plus" @click="openAddDialog">新增支付方式</el-button>
      </div>
  
      <!-- 搜索栏区域 -->
      <div class="search-bar">
        <el-input :prefix-icon="Search" v-model="searchKeyword" placeholder="根据支付方式名称搜索" clearable @input="searchPayMethods" />
      </div>
  
      <!-- 支付方式列表表格 -->
      <el-table
        :data="paginatedPayMethods"
        border
        stripe
        style="width: 100%"
        :header-cell-style="{ background: '#CFCFCFFF', color: '#000000' }"
      >
        <el-table-column prop="id" label="支付方式ID" />
        <el-table-column prop="payName" label="支付方式名称" />
        <el-table-column label="支付方式图标" width="120">
          <template #default="scope">
            <el-image
              v-if="scope.row.payImage"
              :src="scope.row.payImage"
              :preview-src-list="[scope.row.payImage]"
              fit="contain"
              class="pay-image"
            />
            <span v-else>无图标</span>
          </template>
        </el-table-column>
        <el-table-column prop="payInfo" label="支付方式描述" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary"  icon="Edit" size="small" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button type="danger"  icon="Delete" size="small" @click="confirmDeletePayMethod(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页组件 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next"
          :total="totalPayMethods"
        />
      </div>
  
      <!-- 新增支付方式弹窗 -->
      <el-dialog v-model="addDialogVisible" title="新增支付方式">
        <el-form :model="newPayMethod" label-width="120px" ref="addPayMethodForm">
          <el-form-item label="支付方式名称">
            <el-input v-model="newPayMethod.payName" />
          </el-form-item>
          <el-form-item label="支付方式描述">
            <el-input v-model="newPayMethod.payInfo" type="textarea" />
          </el-form-item>
          <el-form-item label="支付方式图标">
            <el-upload
              class="avatar-uploader"
              action="http://localhost:8080/upload"
              :show-file-list="false"
              :on-success="handleImageUploadSuccess"
              :before-upload="beforeImageUpload"
            >
              <img v-if="newPayMethod.payImage" :src="newPayMethod.payImage" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveNewPayMethod">保存</el-button>
            <el-button @click="addDialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
  
      <!-- 编辑支付方式弹窗 -->
      <el-dialog v-model="editDialogVisible" title="编辑支付方式">
        <el-form :model="editPayMethod" label-width="120px" ref="editPayMethodForm">
          <el-form-item label="支付方式名称">
            <el-input v-model="editPayMethod.payName" />
          </el-form-item>
          <el-form-item label="支付方式描述">
            <el-input v-model="editPayMethod.payInfo" type="textarea" />
          </el-form-item>
          <el-form-item label="支付方式图标">
            <el-upload
              class="avatar-uploader"
              action="http://localhost:8080/upload"
              :show-file-list="false"
              :on-success="handleImageUploadSuccess"
              :before-upload="beforeImageUpload"
            >
              <img v-if="editPayMethod.payImage" :src="editPayMethod.payImage" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveEditPayMethod">保存</el-button>
            <el-button @click="editDialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue';
  import Header from '@/views/ui/header.vue';
  import { ElMessageBox, ElMessage } from 'element-plus';
  import { getPayMethodListApi, addPayMethodApi, getPayMethodInfoByIdApi, updatePayMethodInfoApi, deletePayMethodByIdApi } from '@/apis/PayMethodManagerApi';
  import { Calendar, Search } from '@element-plus/icons-vue'
  const payMethodList = ref([]);
  const searchKeyword = ref('');
  const currentPage = ref(1);
  const pageSize = ref(10);
  const totalPayMethods = ref(0);
  const paginatedPayMethods = ref([]);
  const addDialogVisible = ref(false);
  const newPayMethod = reactive({
    payName: '',
    payInfo: '',
    payImage: ''
  });
  const editDialogVisible = ref(false);
  const editPayMethod = ref({});
  
  const fetchPayMethodList = async () => {
    try {
      const res = await getPayMethodListApi();
      payMethodList.value = res.data;
      totalPayMethods.value = payMethodList.value.length;
      applyFiltersAndPagination();
    } catch (error) {
      console.error('获取支付方式列表失败:', error);
    }
  };
  
  const searchPayMethods = () => {
    applyFiltersAndPagination();
  };
  
  const applyFiltersAndPagination = () => {
    let filteredPayMethods = payMethodList.value.filter(payMethod =>
      payMethod.payName.toLowerCase().includes(searchKeyword.value.toLowerCase())
    );
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    paginatedPayMethods.value = filteredPayMethods.slice(start, end);
  };
  
  const handleSizeChange = size => {
    pageSize.value = size;
    applyFiltersAndPagination();
  };
  
  const handleCurrentChange = page => {
    currentPage.value = page;
    applyFiltersAndPagination();
  };
  
  const openAddDialog = () => {
    newPayMethod.payName = '';
    newPayMethod.payInfo = '';
    newPayMethod.payImage = '';
    addDialogVisible.value = true;
  };
  
  const saveNewPayMethod = async () => {
    try {
      await addPayMethodApi(newPayMethod);
      ElMessage.success('新增支付方式成功');
      addDialogVisible.value = false;
      fetchPayMethodList();
    } catch (error) {
      ElMessage.error('新增支付方式失败');
      console.error('新增支付方式失败:', error);
    }
  };
  
  const openEditDialog = payMethod => {
    editPayMethod.value = { ...payMethod };
    editDialogVisible.value = true;
  };
  
  const saveEditPayMethod = async () => {
    try {
      await updatePayMethodInfoApi(editPayMethod.value);
      ElMessage.success('更新支付方式成功');
      editDialogVisible.value = false;
      fetchPayMethodList();
    } catch (error) {
      ElMessage.error('更新支付方式失败');
      console.error('更新支付方式失败:', error);
    }
  };
  
  const confirmDeletePayMethod = payMethodId => {
    ElMessageBox.confirm('确定要删除该支付方式吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        try {
          await deletePayMethodByIdApi(payMethodId);
          ElMessage.success('删除支付方式成功');
          fetchPayMethodList();
        } catch (error) {
          ElMessage.error('删除支付方式失败');
          console.error('删除支付方式失败:', error);
        }
      })
      .catch(() => {
        ElMessage.info('已取消删除');
      });
  };
  
  const handleImageUploadSuccess = (response, uploadFile) => {
    if (response.code === 1) {
      ElMessage.success('图标上传成功');
      if (addDialogVisible.value) {
        newPayMethod.payImage = response.data.url;
      } else if (editDialogVisible.value) {
        editPayMethod.value.payImage = response.data.url;
      }
    } else {
      ElMessage.error(response.message || '图标上传失败');
    }
  };
  
  const beforeImageUpload = (file) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      ElMessage.error('只能上传图片文件');
    }
    return isImage;
  };
  
  onMounted(() => {
    fetchPayMethodList();
  });
  </script>
  
  <style scoped>
  .operation-bar {
    margin-bottom: 10px;
  }
  
  .search-bar {
    display: flex;
    gap: 10px;
    margin-bottom: 10px;
  }
  
  .pagination {
    margin-top: 10px;
    text-align: right;
  }
  
  .pay-image {
    width: 80px;
    height: 80px;
    border-radius: 4px;
    object-fit: contain;
  }
  
  .avatar-uploader .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
  
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  </style>